
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;




public class Query {
	
    String qstring;
    public List termlist;
    int iteration;
    int resultnum=4;
    String Yahooid="NZV4PVfV34F9XCApUVMXK.q_.xlEGRnBDtLtaSQ6iYQgDJhqpTTS3akop5KvIU2THg--";
    
	public Query(String s)
	{
		try{qstring = URLEncoder.encode(s, "UTF-8");}catch(Exception e){System.err.print(e);}
		iteration=0;
		pstring(s);
	}
	
	public void pstring(String s)
	{
		StringTokenizer st = new StringTokenizer(s);
		termlist=new ArrayList();
		while(st.hasMoreTokens())
		{
			termlist.add(st.nextToken());
		}
	}
	
	public Presult runquery(String sites)
	{
		String request = "http://boss.yahooapis.com/ysearch/web/v1/";
	    HttpClient client = new HttpClient();

	    request += qstring + "?";
	    request += "appid=" + Yahooid + "&";
	    request += "count=" + resultnum + "&";
	    request += "sites=" + sites + "&";
	    request += "format=xml";
	    
	    GetMethod method = new GetMethod(request);

	    System.out.println("query: "+qstring);
	    try {
	    	int statusCode = client.executeMethod(method);
	        if (statusCode != HttpStatus.SC_OK) {
	        	System.err.println("Method failed: " + method.getStatusLine());
	        	return null;
	        }
	    } catch (IOException e) {
	    	System.err.println(e.getLocalizedMessage());
	    	return null;
	    }

	    InputStream rstream = null;
	    
	    try {
	    	rstream = method.getResponseBodyAsStream();
	    } catch (IOException e) {
	    	System.err.println(e.getLocalizedMessage());
	    	return null;
	    }

	    try {
	    	return new Presult(rstream);
	    } catch (Exception e) {
	    	System.err.println("cannot create results");
	    	return null;
	    }
	}
	
	public List getList()
	{
		return termlist;
	}
	public int getRound()
	{
		return iteration;
	}
}
